
//
//  Vector_remove.swift
//  SwiftyDSA
//
//  Created by Archer on 2018/8/5.
//  Copyright © 2018年 Archer. All rights reserved.
//

import Foundation

/// 删除元素
extension Vector {
    /// remove all elements 
    @discardableResult
    public func removeAll() -> Int {
        return _remove(from: startIndex, to: endIndex)
    }
    
    @discardableResult
    public func removeFirst() -> Element? {
        if isEmpty { return nil }
        let first = _storage[0]
        remove(at: 0)
        return first
    }
    
    @discardableResult
    public func removeLast() -> Element? {
        if isEmpty { return nil }
        let last = _storage[_size - 1]
        remove(at: _size - 1)
        return last
    }
    
    @discardableResult
    public func remove(at index: Int) -> Int {
        return _remove(from: index, to: index + 1)
    }
    
    @discardableResult
    public func remove(at range: CountableRange<Index>) -> Int {
        return _remove(from: range.lowerBound, to: range.upperBound)
    }
    
    @discardableResult
    public func remove(at range: CountableClosedRange<Index>) -> Int {
        return _remove(from: range.lowerBound, to: range.upperBound.advanced(by: 1))
    }
    
    /// 返回被删除元素的数目
    /// Note: 'to' is not include(a.k.a CountableRange)
    func _remove(from startIndex: Index, to endIndex: Index) -> Int {
        precondition(startIndex >= 0 && startIndex <= endIndex, "Index不能为负数且startIndex不能大于endIndex")
        precondition(endIndex <= self.endIndex, "指定区间(\(startIndex)-\(endIndex))超过\(self)的容量")
        let removedCount = endIndex - startIndex
        for i in endIndex..<self.endIndex {
            _storage[i - removedCount] = _storage[i]
        }
        _size -= removedCount
        _shrink()
        return removedCount
    }
}
